/*
 * @Date: 2019-10-13 14:05:24
 * @Author: jiangsenlin
 * @Description: 下载文件
 */


import moment from 'moment';

const ajax = (url, options = {}) => {
  window.URL = window.URL || window.webkitURL;
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    if (options.responseType) xhr.responseType = options.responseType;
    xhr.onreadystatechange = function() {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
          resolve(xhr);
        } else {
          reject(xhr);
        }
      }
    };
    xhr.send();
  });
};

function downloadFile(content, filename) {
  let a = document.createElement('a');
  const blob = new Blob([content]);
  const url = window.URL.createObjectURL(blob);
  a.href = url;
  a.download = filename;
  a.click();
  window.URL.revokeObjectURL(url);
}

const download = async (url, name) => {
  const result = await ajax(url, { responseType: 'blob' });
  if (result.response) {
    const filename = `${name || moment(new Date()).format('YYYYMMDDHHmmss')}.${url.replace(
      /(.*\.)/,
      '',
    )}`;
    downloadFile(result.response, filename);
    return Promise.resolve('success');
  } else {
    return Promise.reject('error');
  }
};

export default download;
